package com.hyl.config;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Description TODO
 * @Author hyl
 * @Date 2023/5/18 11:40
 **/
//自定义过滤器
@WebFilter(urlPatterns = {"/user/*","/role/*"})
public class LoginFilter implements Filter {
	//初始化方法
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//初始化处理
		System.out.println("过滤器初始化");
	}

	@Override
	public void doFilter(ServletRequest servletRequest,
	                     ServletResponse servletResponse,
	                     FilterChain filterChain) throws IOException, ServletException {
		//过滤处理
		HttpServletRequest request= (HttpServletRequest) servletRequest;
		HttpServletResponse response= (HttpServletResponse) servletResponse;
//        String requestURI=request.getRequestURI();
//        System.out.println("链接:"+requestURI+"进入过滤器");
		HttpSession session=request.getSession();
		if(session.getAttribute("userSession")==null){ //用户没有登入
			//非法请求，直接跳转到登陆界面
			String serverPath=request.getScheme()+"://"+request.getServerName()+":"
					+request.getServerPort()+request.getContextPath()+"/index.jsp";
			response.sendRedirect(serverPath);
		}else{
			//正常登录，放行
			filterChain.doFilter(request,response);
		}
	}

	@Override
	public void destroy() {
		//释放资源
		System.out.println("过滤器销毁");
	}
}